﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.Cecil;
using devtm.Aop.Extensions;
using devtm.Aop.Emit;

namespace devtm.Aop.Extensions
{
    
    public static class EmitExt
    {


        public static void Insert(this CilWorker gen, EmitStatement code)
        {
            code.Compile(gen);
        }

        public static void Insert(this CilWorker gen, EmitExpression code)
        {
            var c = new EmitExpressionStatement(code);
            c.Compile(gen);
        }

        public static EmitAssignStatement Set(this EmitExpression left, EmitExpression right)
        {
            EmitAssignStatement s = new EmitAssignStatement(left, right);
            return s;
        }


        public static Instruction GetStockLocation(this CilWorker gen, EmitVariableReferenceExpression variable)
        {
            return gen.GetStockLocation(variable.Variable);
        }


        public static Instruction SetStockLocation(this CilWorker gen, EmitVariableReferenceExpression variable)
        {
            return gen.SetStockLocation(variable.Variable);
        }


        [System.Diagnostics.DebuggerStepThrough]
        public static bool Is(this Instruction instruction, params Code[] codes)
        {

            foreach (Code o in codes)
                if (o == instruction.OpCode.Code)
                    return true;

            return false;

        }


        public static EmitExpression[] ConvertInEmitExpression(this Collection<ParameterDefinition> parameters, params int[] indexes)
        {

            int cntParameters = parameters.Count;
            List<EmitExpression> args = new List<EmitExpression>();

            for (int i = 0; i < cntParameters; i++)           
                if (indexes == null || indexes.Length == 0 || indexes.Contains(i))
                    args.Add(new EmitArgumentReferenceExpression(i));
           
            return args.ToArray(); ;

        }



    }
}
